<template>
  <div class="app-container">
    <div class="main-con" style="height: calc(100% - 0rem)">
      <div class="summary-con" style="height: 115px">
        <div class="right-con">
          <div class="img">
            <img src="@/assets/images/average.png" alt="" />
          </div>
          <div class="item-wrap">
            <div class="title">今日交易</div>
            <div>
              <span class="num">{{ debitCardAnalysis.todayCount }}</span> <span class="unit">次</span>
            </div>
          </div>
        </div>
        <div class="center-con">
          <div class="img">
            <img src="@/assets/images/average.png" alt="" />
          </div>
          <div class="item-wrap">
            <div class="title">今日刷卡</div>
            <div>
              <span class="num">{{ debitCardAnalysis.todayAmount }}</span>
            </div>
          </div>
        </div>
        <div class="right-con">
          <div class="img">
            <img src="@/assets/images/average.png" alt="" />
          </div>
          <div class="item-wrap">
            <div class="title">近7日交易</div>
            <div>
              <span class="num">{{ debitCardAnalysis.sevenDayCount }}</span> <span class="unit">次</span>
            </div>
          </div>
        </div>
        <div class="center-con">
          <div class="img">
            <img src="@/assets/images/average.png" alt="" />
          </div>
          <div class="item-wrap">
            <div class="title">近7日刷卡</div>
            <div>
              <span class="num">{{ debitCardAnalysis.sevenDayAmount }}</span>
            </div>
          </div>
        </div>
        <div class="center-con">
          <div class="img">
            <img src="@/assets/images/average.png" alt="" />
          </div>
          <div class="item-wrap">
            <div class="title">近1月交易次数</div>
            <div>
              <span class="num">{{ debitCardAnalysis.oneMonthCount }}</span> <span class="unit">次</span>
            </div>
          </div>
        </div>
        <div class="center-con">
          <div class="img">
            <img src="@/assets/images/average.png" alt="" />
          </div>
          <div class="item-wrap">
            <div class="title">近1月刷卡</div>
            <div>
              <span class="num">{{ debitCardAnalysis.oneMonthAmount }}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="summary-con" style="height: 110px">
        <div class="right-con">
          <div class="img">
            <img src="@/assets/images/average.png" alt="" />
          </div>
          <div class="item-wrap">
            <div class="title">近6月交易</div>
            <div>
              <span class="num">{{ debitCardAnalysis.sixMonthCount }}</span> <span class="unit">次</span>
            </div>
          </div>
        </div>
        <div class="center-con">
          <div class="img">
            <img src="@/assets/images/average.png" alt="" />
          </div>
          <div class="item-wrap">
            <div class="title">近6月刷卡</div>
            <div>
              <span class="num">{{ debitCardAnalysis.sixMonthAmount }}</span>
            </div>
          </div>
        </div>
        <div class="center-con">
          <div class="img">
            <img src="@/assets/images/average.png" alt="" />
          </div>
          <div class="item-wrap">
            <div class="title">近1年交易</div>
            <div>
              <span class="num">{{ debitCardAnalysis.oneYearCount }}</span> <span class="unit">次</span>
            </div>
          </div>
        </div>
        <div class="center-con">
          <div class="img">
            <img src="@/assets/images/average.png" alt="" />
          </div>
          <div class="item-wrap">
            <div class="title">近1年刷卡</div>
            <div>
              <span class="num">{{ debitCardAnalysis.oneYearAmount }}</span>
            </div>
          </div>
        </div>
        <div class="right-con">
          <div class="img">
            <img src="@/assets/images/average.png" alt="" />
          </div>
          <div class="item-wrap">
            <div class="title">总交易次数</div>
            <div>
              <span class="num">{{ debitCardAnalysis.totalCount }}</span> <span class="unit">次</span>
            </div>
          </div>
        </div>
        <div class="right-con">
          <div class="img">
            <img src="@/assets/images/average.png" alt="" />
          </div>
          <div class="item-wrap">
            <div class="title">总刷卡金额</div>
            <div>
              <span class="num">{{ debitCardAnalysis.totalAmount }}</span> <span class="unit"></span>
            </div>
          </div>
        </div>
      </div>
      <div class="title-con" style="margin-top: 18px">
        <div class="title">POS机统计</div>
        <div class="operate-btn-con">
          <el-radio-group v-model="radioVal" @change="handleRadioChange">
            <el-radio-button label="POS机统计表格" />
            <el-radio-button label="近6月刷卡金额柱状图" />
            <el-radio-button label="近6月刷卡金额折线图" />
          </el-radio-group>
        </div>
      </div>
      <div class="content-con">
        <div v-show="radioVal === '近6月刷卡金额柱状图'" class="chart" id="chartBar" style="height: calc(100% - 225px); margin-top: -10px"></div>
        <div v-show="radioVal === '近6月刷卡金额折线图'" class="chart" id="chartLine" style="height: calc(100% - 225px); margin-top: -10px"></div>
        <el-table v-show="radioVal === 'POS机统计表格'" v-loading="loading" :data="debitCardAnalysis.posTableList" height="calc(100% - 245px)">
          <el-table-column label="序号" width="50" type="index" align="center">
            <template #default="scope">
              <span>{{ scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="POS机" align="center" prop="nameCode" />
          <el-table-column label="今日交易次数" align="center" prop="todayCount" />
          <el-table-column label="今日刷卡金额" align="center" prop="todayAmount" />
          <!-- <el-table-column label="近7日交易次数" align="center" prop="sevenDayCount" />
          <el-table-column label="近7日刷卡金额" align="center" prop="sevenDayAmount" /> -->
          <el-table-column label="近1月交易次数" align="center" prop="oneMonthCount" />
          <el-table-column label="近1月刷卡金额" align="center" prop="oneMonthAmount" />
          <!-- <el-table-column label="近3月交易次数" align="center" prop="threeMonthCount" />
          <el-table-column label="近3月刷卡金额" align="center" prop="threeMonthAmount" /> -->
          <el-table-column label="近6月交易次数" align="center" prop="sixMonthCount" />
          <el-table-column label="近6月刷卡金额" align="center" prop="sixMonthAmount" />
          <el-table-column label="近1年交易次数" align="center" prop="oneYearCount" />
          <el-table-column label="近1年刷卡金额" align="center" prop="oneYearAmount" />
          <el-table-column label="总交易次数" align="center" prop="totalCount" />
          <el-table-column label="总刷卡金额" align="center" prop="totalAmount" />
        </el-table>
      </div>
    </div>
  </div>
</template>

<script setup name="DebitCardAnalysis">
import dayjs from 'dayjs'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { getPosStatics } from '@/api/invest/statisticAnalysis'
const { proxy } = getCurrentInstance()
const { account_type } = proxy.useDict('account_type')

const loading = ref(true)
const total = ref(0)
const radioVal = ref('POS机统计表格')
const dateValidate = (rules, value, callback) => {
  const dateType = rules.dateType || 'days'
  const num = rules.num || 31
  const dateString = rules.dateString || '天'
  const message = rules.message || `时间跨度不能超过${num}${dateString}`

  if (value && value.length === 2) {
    const start = value[0]
    const end = value[1]
    if (dayjs(end).diff(dayjs(start), dateType) > num) {
      queryParams.value.time = [start, dayjs(start).add(59, 'months')]
      ElMessage.warning(message)
    }
  }
}

const data = reactive({
  queryParams: {
    type: 1,
    time: null,
    dataType: null,
    id: null
  },
  rules: {
    time: [{ validator: dateValidate, dateType: 'months', num: 59, dateRange: '月', message: '时间跨度不能大于60个月，默认选择开始日期的24个月' }]
  }
})

const { queryParams, rules } = toRefs(data)
const handleChange = (id) => {
  queryParams.value.dataType = id
  getList()
}
const today = new Date()
const end = today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' + today.getDate()).slice(-2)
const start = end
queryParams.value.time = [start, end]

const firstChooseDate = ref('')
const calendarChange = (val) => {
  firstChooseDate.value = val[0].getTime()
  if (val[1]) firstChooseDate.value = ''
}

const debitCardAnalysis = ref({
  debetBalance: '',
  creditAvailableLimit: '',
  creditBalance: '',
  investBalance: '',
  debitBalance: '',
  posList: []
})
const chartData = ref({
  name: [],
  value1: []
})

function getList() {
  loading.value = true
  chartData.value = { name: [], value1: [] }
  const { type, time, id, dataType } = queryParams.value
  let formatValue = 'YYYY-MM-DD'
  if (type === 1) {
    formatValue = 'YYYY-MM-DD'
  } else if (type === 2) {
    formatValue = 'YYYY-MM'
  } else {
    formatValue = 'YYYY'
  }
  const params = {
    type,
    startTime: time && time.length > 0 ? dayjs(time[0]).format(formatValue) : '',
    endTime: time && time.length > 0 ? dayjs(time[1]).format(formatValue) : '',
    id,
    dataType
  }
  getPosStatics(params).then((response) => {
    loading.value = false
    debitCardAnalysis.value = { ...response.data }
    debitCardAnalysis.value.posList.map((item) => {
      return {
        name: item.pos,
        value: item.amount
      }
    })
    response.data.posList.map((item) => {
      chartData.value.name.push(item.pos)
      chartData.value.value1.push(item.amount)
    })
    handleRadioChange(currentType.value)
  })
}

function handleQuery() {
  getList()
}

function resetQuery() {
  proxy.resetForm('queryRef')
  queryParams.value.id = null
  queryParams.value.dataType = null
  total.value = 0
  handleQuery()
}

const drawBar = (data) => {
  if (document.getElementById('chartBar') === null) {
    return
  }
  echarts.dispose(document.getElementById('chartBar'))
  const myChart = echarts.init(document.getElementById('chartBar'))

  const option = {
    legend: {
      // 图示例样式
      show: true,
      top: 50,
      right: 50,
      itemGap: 20
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function (params) {
        return params[0].name + '<br>' + '刷卡金额：' + params[0].value + '元'
      }
    },
    grid: {
      left: '5%',
      right: '5%',
      bottom: '5%',
      containLabel: true
    },
    xAxis: [
      {
        type: 'category',
        data: data.name,
        axisTick: {
          alignWithLabel: true // 刻度线是否与标签对齐，默认false
        },
        // 设置 X 轴线条粗细
        axisLine: {
          lineStyle: {
            width: 1, // 根据需求调整数值大小，单位是像素
            color: '#999'
          }
        }
      }
    ],
    yAxis: [
      {
        type: 'value',
        axisTick: {
          show: false // 默认为true，如果要隐藏，则改为 false
        },
        axisLine: {
          show: true,
          lineStyle: {
            width: 1,
            color: '#999'
          }
        }
      }
    ],
    series: [
      {
        data: data.value1,
        type: 'bar',
        barWidth: 20, // 根据需求调整数值大小，单位是像素
        itemStyle: {
          // 此处可以是一个固定颜色值，也可以是一个回调函数根据数据动态计算颜色
          color: function (params) {
            // 这里可以根据需要设置不同的颜色，比如根据数据值
            if (params.data <= 0) {
              return 'green'
            } else if (params.data > 0) {
              return 'red'
            }
          }
        }
      }
    ],
    // 添加点击事件的处理函数
    emphasis: {
      // itemStyle: {
      //   color: '#2283cf',
      //   barWidth: 20 // 根据需求调整数值大小，单位是像素
      // },
      // barWidth: 24 // 根据需求调整数值大小，单位是像素
    }
  }

  myChart.setOption(option)
}

const drawLine = (data) => {
  if (document.getElementById('chartLine') === null) {
    return
  }
  echarts.dispose(document.getElementById('chartLine'))
  const myChart = echarts.init(document.getElementById('chartLine'))

  const option = {
    grid: {
      left: '5%',
      right: '5%',
      bottom: '5%',
      containLabel: true
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function (params) {
        return params[0].name + '<br>' + '刷卡金额：' + params[0].value + '元'
      }
    },
    xAxis: {
      type: 'category',
      data: data.name,
      axisTick: {
        alignWithLabel: true
      },
      axisLine: {
        lineStyle: {
          width: 1,
          color: '#999'
        }
      }
    },
    yAxis: {
      type: 'value',
      axisTick: {
        show: false
      },
      axisLine: {
        show: true,
        lineStyle: {
          width: 1,
          color: '#999'
        }
      }
    },
    series: [
      {
        data: data.value1,
        type: 'line',
        lineStyle: {
          color: '#4181c9'
        },
        itemStyle: {
          // 此处可以是一个固定颜色值，也可以是一个回调函数根据数据动态计算颜色
          color: function (params) {
            // 这里可以根据需要设置不同的颜色，比如根据数据值
            if (params.data <= 0) {
              return 'green'
            } else if (params.data > 0) {
              return 'red'
            }
          }
        },
        smooth: true,
        symbol: 'emptyCircle',
        areaStyle: {
          color: new echarts.graphic.LinearGradient(
            0,
            0,
            0,
            1,
            [
              {
                offset: 0,
                color: 'rgba(65,129,201, 0.70)'
              },
              {
                offset: 1,
                color: 'rgba(65,129,201, 0.10)'
              }
            ],
            false
          ),
          shadowColor: 'rgba(65,129,201, 0.10)',
          shadowBlur: 10
        }
      }
    ]
  }

  myChart.setOption(option)
}

const currentType = ref('近1年刷卡金额柱状图')
const handleRadioChange = (type) => {
  currentType.value = type
  switch (type) {
    case '近6月刷卡金额柱状图':
      drawBar(chartData.value)
      break
    case '近6月刷卡金额折线图':
      drawLine(chartData.value)
      break
    default:
      break
  }
}
getList()
</script>
